<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="text">--</div>
  <script>
    // var name = 1;
    var ref = (val) => {
      const obj = {
        _value: val,
        _isRef: true,
        get value() {
          console.log("get", this._value)
          return this._value;
        },
        set value(val) {
          console.log("set", val)
          this._value = val;
          document.querySelector("#text").innerHTML = val;
        }
      }
      return obj;
    }

    var c = ref("1");
    var axios = (time = 500, val) => {
      return new Promise((resolve) => {
        setTimeout(() => {
          console.log("axios", val)
          resolve(val);
        }, time)
      })
    }
    function competeUpdate() {
      let cleanup = null;//永远存储最新的
      function update(cb) {
        function onInvalidate(fn) {
          cleanup = fn;
        }
        if (cleanup) {
          cleanup();
        }
        cb(onInvalidate)
      }
      return update;
    }
    const onChange = competeUpdate();
    onChange(async (onInvalidate) => {
      let inValid = false;
      // console.log("onInvalidate", onInvalidate)
      onInvalidate(() => {
        console.log("第一次的onInvalidate被调用")
        inValid = true;
      })
      let result = await axios(1000, "第一次");
      console.log("第一次的inValid", inValid)
      if (!inValid) {
        c.value = result;
      }
    })
    onChange(async (onInvalidate) => {
      let inValid = false;
      onInvalidate(() => {
        console.log("第二次的onInvalidate被调用")
        inValid = true;
      })
      let result = await axios(200, "第二次");
      if (!inValid) {
        c.value = result;
      }
    })

  </script>
</body>

</html>